package com.unohacha.qqj.fzdr;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.loader.ImageLoader;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.widget.common.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.CatData;
import com.unohacha.qqj.fzdr.bean.ImgBean;
import com.unohacha.qqj.fzdr.ui.activity.FindImgDetialActivity;
import com.unohacha.qqj.fzdr.util.GlideImageLoader;
import com.unohacha.qqj.fzdr.util.GlideImageLoaderForPicker;
import com.unohacha.qqj.fzdr.util.GlideImgLoader;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 以图找图 第一级页面
 */
public class FindImageByImageActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener{

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    //    @BindView(R.id.image_grid_layout)
//    MyGridView imageGridLayout;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recycleview)
    RecyclerView recycleview;
    private int a;
    private List<CatData> list;
    private List<CatData.Two> listTwo;
    private int catId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_supply_demand;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText("分类");
        commonRightImage.setVisibility(View.INVISIBLE);
        list = new ArrayList<>();
        commonRightImage.setVisibility(View.INVISIBLE);
//        imageGridLayout.setOnItemClickListener(this);
        WindowManager manager = getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        a = outMetrics.widthPixels - 50;
        GridLayoutManager layoutManage = new GridLayoutManager(this, 4);
        recycleview.setLayoutManager(layoutManage);
        getData();
        initImagePicker();
    }
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImgLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(1);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }
    private class MyAdapter extends BaseQuickAdapter<CatData.Two, BaseViewHolder> {

        public MyAdapter(int layoutResId, @Nullable List<CatData.Two> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, CatData.Two item) {
            final ImageView imageView = (ImageView) helper.getView(R.id.supply_item_type_image);
            imageView.setMinimumWidth(a / 4);
            imageView.setMinimumHeight(a / 4);
            Glide.with(FindImageByImageActivity.this)
                    .load(item.getPic())
                    .error(R.mipmap.ic_default_photo)
                    .override(a / 4, a / 4)
                    .into(imageView);
            //加载圆形头像
//            Glide.with(FindImageByImageActivity.this).load(item.getPic())
//                    .asBitmap().centerCrop().into(new BitmapImageViewTarget(imageView) {
//                @Override
//                protected void setResource(Bitmap resource) {
//                    RoundedBitmapDrawable circularBitmapDrawable =
//                            RoundedBitmapDrawableFactory.create(getResources(), resource);
//                    circularBitmapDrawable.setCircular(true);
//                    imageView.setImageDrawable(circularBitmapDrawable);
//                }
//            });
            helper.setText(R.id.supply_item_type_text, item.getName());
        }
    }

    @OnClick(R.id.common_back)
    public void onViewClicked() {
        finish();
    }
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        catId=listTwo.get(position).getId();
        Intent intent = new Intent(FindImageByImageActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 1007);

    }
    private void getData(){
        showLoading();
        SuperHttp.post("api/supplyinfo/supplyCate")
                .addParam("token",Prefer.getInstance().getToken())
                .addParam("typeid","2")
                .request(new SimpleCallBack<BaseBean<List<CatData>>>() {
                    @Override
                    public void onSuccess(BaseBean<List<CatData>> data) {
                        if(data.getCode()==0){
                            ToastUtils.showT("暂无数据");
                            return;
                        }
                        list.clear();
                        list.addAll(data.getData());
                        for(int i=0;i<list.size();i++){
                            if(list.get(i).getId()==1){
                                listTwo=data.getData().get(i).getTwo();
                                MyAdapter adapter = new MyAdapter(R.layout.activity_supply_demand_grid_item, data.getData().get(i).getTwo());
                                adapter.setOnItemClickListener(FindImageByImageActivity.this);
                                recycleview.setAdapter(adapter);
                                if (mRefreshLayout.isRefreshing()) {
                                    mRefreshLayout.finishRefresh();
                                }
                            }
                        }

                        hideLoading();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        hideLoading();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 1007) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);

                showLoading();
                String token= Prefer.getInstance().getToken();
                SuperHttp.upload("api/filepic/filePic")
                        .addParam("type","1")
                        .addParam("token",token)
                        .addFile("file", new File(images.get(0).path))
                        .request(new SimpleCallBack<BaseBean<List<ImgBean>>>() {
                            @Override
                            public void onSuccess(BaseBean<List<ImgBean>> data) {
                                if(data.getCode()==1){
                                    Intent intent=new Intent(FindImageByImageActivity.this, FindImgDetialActivity.class);
                                    intent.putExtra("img_url",data.getData().get(0).getSrc());
                                    intent.putExtra("catId",catId+"");
                                    startActivity(intent);
                                }
                                hideLoading();
                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                ToastUtil.showCustomToast("获取失败");
                                hideLoading();
                            }
                        });

            } else {
            }
        }
    }
}
